<template>
  <FormGenerator
    ref="FormGenerator"
    :formLists.sync="formLists"
    :formAttrs.sync="formAttrs"
    :hideSaveBtn="hideSaveBtn"
    :enabled="enabled"
    @save="handleSave"
    @update="hanldeUpdate"
  />
</template>

<script>
import FormGenerator from "@/components/formGenerator/formGenerator";
import { deepClone, setFormValue } from "../components/formGenerator/utils";
import { setConfig } from "@/components/formGenerator/utils/config";
import "./common/initPc";
import "./common/initPhone";
export default {
  name: "FGDesigner",
  components: {
    FormGenerator
  },
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update"
  },
  props: {
    // 用于回显的旧数据表单,包括表单属性和表单组件
    value: {
      type: [Object, String],
      default: () => {}
    },
    // 传入对应的key & value
    form: {
      type: Object,
      default: () => {}
    },
    // 隐藏保存按钮
    hideSaveBtn: {
      type: Boolean,
      default: false
    },
    // 编辑器时是否可以点击操作
    enabled: {
      type: Boolean,
      default: false
    },
    // 默认组件库，可以通过外部操作来替换
    defaultComs: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      formLists: [], // 回显的旧数据
      formAttrs: {}
    };
  },

  created() {
    if (this.defaultComs) setConfig(this.defaultComs);
    let value = deepClone(this.value);
    if (typeof this.value === "string") {
      value = JSON.parse(this.value || "{}");
    }
    if (value && value.list) {
      this.formLists = setFormValue(
        deepClone(this.value.list || []),
        this.form
      );
      this.formAttrs = deepClone(value);
      delete this.formAttrs?.list;
      console.log("formLists", this.formLists);
      console.log("formAttrs", this.formAttrs);
    }
  },
  methods: {
    // 保存
    handleSave(list, attrs) {
      const newValue = { ...attrs, list };
      this.$emit("update", newValue);
      this.$emit("save", newValue, list, attrs);
    },
    // 数据更新
    hanldeUpdate(list, attrs) {
      const newValue = { ...attrs, list };
      this.$emit("update", newValue);
      this.$emit("change", newValue, list, attrs);
    },
    validate(cb) {
      this.$refs.FormGenerator.validate((valid, message) => {
        cb(valid, message, this.value);
      });
    },
    submit(cb) {
      cb(this.value);
    }
  }
};
</script>

<style lang="scss" scoped></style>
